<template>
  <view class="container">
    <!-- 对话内容区域 -->
    <scroll-view class="content" :scroll-y="true" :scroll-top="scrollTop">
      <view class="message-list">
        <view 
          v-for="(message, index) in messages" 
          :key="index" 
          :class="['message', message.role]"
        >
          <view class="message-content">
            <ua-markdown :source="message.content" :showLine="false" />
          </view>
          <view class="message-time">{{ message.time }}</view>
        </view>
        
        <!-- 流式响应显示区域 -->
        <view 
          v-if="streamingMessage.content || streamingMessage.loading" 
          class="message assistant"
        >
          <view class="message-content">
            <ua-markdown :source="streamingMessage.content" :showLine="false"/>
            <view class="typing-indicator" v-if="streamingMessage.loading">
              <view class="dot"></view>
              <view class="dot"></view>
              <view class="dot"></view>
            </view>
          </view>
          <view class="message-time">{{ streamingMessage.time }}</view>
        </view>
        
        <!-- 连接状态提示 -->
        <view v-if="!socketOpen && !socketConnected" class="connection-status">
          <u-loading-icon mode="circle" size="24" />
          <text class="status-text">正在连接AI服务...</text>
        </view>
      </view>
    </scroll-view>
    <!-- 输入区域 -->
    <view class="input-container" :style="{bottom: inputBottom+'px'}">
      <input 
        class="message-input" 
        v-model="userInput" 
        placeholder="请输入您的问题..." 
        @confirm="sendMessage"
        :adjust-position="false"
        ref="messageInput"
        @focus="focusTextarea"
        @blur="blurTextarea"
        :disabled="!socketOpen"
      />

      <view class="flooer_rpic a" @click="sendMessage">
        <image src="../../static/fasong.png" mode=""></image>
      </view>
    </view>
  </view>
</template>

<script>
import UaMarkdown from '@/components/ua2-markdown/ua-markdown.vue';
import setting from '@/common/config.js';

export default {
  components: {
    UaMarkdown
  },
  data() {
    return {
      conversationId: '', // 添加conversationId属性
      dialogue: {
        title: 'AI助手'
      },
      messages: [],
      streamingMessage: {
        content: '',
        time: '',
        loading: false
      },
      userInput: '',
      isLoading: false,
      responseBuffer: '', // 响应缓冲区
      keyboardHeight: 0, // 键盘高度
      inputBottom: 30,
      scrollTop: 0,
      scrollToBottomTimer: null, // 滚动到底部的定时器
      socketOpen: false,
      socketConnected: false, // 添加连接状态跟踪
      typeingText: "",
      // 添加连接Promise相关变量
      connectionPromise: null,
      connectionResolve: null,
      connectionReject: null,
      connectionTimeout: null
    };
  },

  onLoad(options) {
    console.log('页面加载参数:', options);
    // 监听键盘高度变化事件
      uni.onKeyboardHeightChange((res) => {
        if (res.height > 0) {
          this.inputBottom = res.height + 4;
        } else {
          this.inputBottom = 30;
        }
      });
    // 初始化 WebSocket 连接
    this.initWebSocket();
    
    // 检查是否有conversationId参数，如果有则获取对话详情
    if (options.conversationId) {
      const conversationId = options.conversationId;
      this.conversationId = conversationId; // 保存conversationId到data中
      console.log('获取对话详情，ID:', conversationId);
      this.getConversationDetail(conversationId);
    } else {
      // 获取传递的参数
      let title = '';
      if (options.title) {
        title = decodeURIComponent(options.title);
      } else if (options.question) {
        title = decodeURIComponent(options.question);
      }
      
      console.log('创建新对话，标题:', title);
      
      if (title) {
        this.dialogue = {
          title: title
        };
        
        // 添加基于问题标题的初始消息
        this.messages.push({
          role: 'user',
          content: `请解释一下：${title}`,
          time: this.formatTime(new Date())
        });
        
        // 使用nextTick确保页面渲染完成后再发送请求
        this.$nextTick(() => {
          // 延迟执行WebSocket连接和初始请求，不阻塞页面渲染
          setTimeout(() => {
            // 等待WebSocket连接建立后获取AI回复
            this.waitForConnection()
              .then(() => {
                // 获取AI回复
                this.getAIResponse(`请解释一下：${title}`);
              })
              .catch((error) => {
                console.error('WebSocket连接失败，无法获取初始回复:', error);
                uni.showToast({
                  title: '连接失败，无法获取回复',
                  icon: 'none'
                });
              });
          }, 100); // 短暂延迟确保页面渲染完成
        });
      }
    }
    
    // 页面加载完成后自动聚焦到输入框
    this.$nextTick(() => {
      setTimeout(() => {
        if (this.$refs.messageInput) {
          this.$refs.messageInput.focus();
        }
      }, 500);
    });
  },
  
  onUnload() {
    // 取消监听键盘高度变化事件
    uni.offKeyboardHeightChange(()=>{});
    
    // 清理滚动定时器
    if (this.scrollToBottomTimer) {
      clearTimeout(this.scrollToBottomTimer);
    }
    
    // 关闭 WebSocket 连接
    if (this.socketOpen) {
      uni.closeSocket();
    }
    
    // 上传对话记录到服务器
    if (this.messages.length > 0){
      this.uploadConversation();
    }
  },
  
  methods: {
    formatTime(date) {
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      const hours = date.getHours().toString().padStart(2, '0');
      const minutes = date.getMinutes().toString().padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}`;
    },

    // 初始化 WebSocket 连接
    initWebSocket() {
      const token = uni.getStorageSync('token') || '';
      // const url = setting.xunfeiws + (token ? "?Authorization=Bearer " + token : "");
      const url = setting.xunfeiws + (token ? "?Authorization=" + token : "");
      
      // 创建连接Promise，用于等待连接建立
      this.connectionPromise = new Promise((resolve, reject) => {
        this.connectionResolve = resolve;
        this.connectionReject = reject;
        
        // 设置连接超时
        this.connectionTimeout = setTimeout(() => {
          reject(new Error('WebSocket connection timeout'));
        }, 10000); // 10秒超时
      });
      
      uni.connectSocket({
        url: url
      });
      
      uni.onSocketOpen(() => {
        console.log('WebSocket连接已打开');
        this.socketOpen = true;
        // 清除超时定时器
        if (this.connectionTimeout) {
          clearTimeout(this.connectionTimeout);
        }
        // 解决连接Promise
        if (this.connectionResolve) {
          this.connectionResolve();
        }
      });
      
      uni.onSocketError((error) => {
        console.log('WebSocket连接失败:', error);
        this.socketOpen = false;
        // 清除超时定时器
        if (this.connectionTimeout) {
          clearTimeout(this.connectionTimeout);
        }
        // 拒绝连接Promise
        if (this.connectionReject) {
          this.connectionReject(error);
        }
        uni.showToast({
          title: '连接失败，请稍后重试',
          icon: 'none'
        });
      });
      
      uni.onSocketMessage((res) => {
        console.log('WebSocket onSocketMessage');
        this.handleSocketMessage(res);
      });
      
      uni.onSocketClose(() => {
        console.log('WebSocket连接已关闭');
        this.socketOpen = false;
        // 如果连接已关闭，重置连接Promise
        this.connectionPromise = null;
      });
    },
    
    // 处理 WebSocket 消息
    handleSocketMessage(res) {
      console.log('收到服务器内容:', res);
      
      if (res.data === "[DONE]") {
        this.isLoading = false;
        this.streamingMessage.loading = false;
        
        // 将完整消息添加到消息列表
        this.messages.push({
          role: 'assistant',
          content: this.typeingText,
          time: this.streamingMessage.time
        });
        
        // 重置流式消息状态
        this.streamingMessage.content = '';
        this.typeingText = '';
        this.scrollToBottom();
        return;
      }
      
      try {
        if (res.data!="null"){
          this.typeingText += res.data;
          this.streamingMessage.content = this.typeingText;
          this.scrollToBottom();
        }
      } catch (e) {
        console.error('解析消息失败:', e);
      }
    },

    // 滚动到底部方法
    scrollToBottom() {
      // 使用$nextTick确保DOM更新完成
      this.$nextTick(() => {
        // 先将scrollTop设为0，然后再设为一个大值，确保能够触发滚动
        this.scrollTop = 0;
        this.$nextTick(() => {
          this.scrollTop = 999999;
        });
      });
    },

    focusTextarea(e) {
      // 键盘高度已经通过uni.onKeyboardHeightChange监听处理
      this.scrollToBottom();
    },
    blurTextarea(e) {
      // 键盘高度已经通过uni.onKeyboardHeightChange监听处理
      this.scrollToBottom();
    },

    sendMessage() {
      if (!this.userInput.trim() || this.isLoading) return;
      
      // 检查 WebSocket 是否已连接
      if (!this.socketOpen) {
        uni.showToast({
          title: '连接尚未建立，请稍后重试',
          icon: 'none'
        });
        return;
      }
      
      // 添加用户消息
      const userMessage = {
        role: 'user',
        content: this.userInput,
        time: this.formatTime(new Date())
      };
      
      this.messages.push(userMessage);
      this.scrollToBottom(); // 发送消息后滚动到底部
      const question = this.userInput;
      this.userInput = '';

      // 调用 WebSocket 发送消息
      this.getAIResponse(question);
    },
    
    getAIResponse(question) {
      // 设置加载状态
      this.isLoading = true;
      this.streamingMessage.content = '';
      this.streamingMessage.time = this.formatTime(new Date());
      this.streamingMessage.loading = true;
      this.typeingText = ''; // 重置响应缓冲区
      this.scrollToBottom(); // 开始加载响应时滚动到底部

      // 构造包含上下文的完整消息
      const conversationData = {
        messages: [...this.messages], // 包含所有历史消息
        question: question // 当前问题
      };

      // 等待 WebSocket 连接建立后再发送消息
      this.waitForConnection()
        .then(() => {
          // 通过 WebSocket 发送消息
          uni.sendSocketMessage({
            data: JSON.stringify(conversationData),
            success: () => {
              console.log('消息发送成功');
            },
            fail: (err) => {
              console.error('消息发送失败:', err);
              uni.showToast({
                title: '消息发送失败，请稍后重试',
                icon: 'none'
              });
              this.isLoading = false;
              this.streamingMessage.loading = false;
            }
          });
        })
        .catch((error) => {
          console.error('WebSocket连接失败:', error);
          uni.showToast({
            title: '连接失败，无法发送消息',
            icon: 'none'
          });
          this.isLoading = false;
          this.streamingMessage.loading = false;
        });
    },
    
    // 等待WebSocket连接建立
    async waitForConnection() {
      // 如果连接已建立，直接返回
      if (this.socketOpen) {
        return Promise.resolve();
      }
      
      // 如果还没有连接Promise，说明连接尚未初始化
      if (!this.connectionPromise) {
        throw new Error('WebSocket连接尚未初始化');
      }
      
      // 等待连接建立
      return this.connectionPromise;
    },
    
    // 上传对话记录到服务器
    uploadConversation() {
      // 构造对话内容，将messages转为json字符串
      const content = JSON.stringify(this.messages);
      
      // 构造请求参数，严格按照接口字段定义
      const params = {
        title: this.dialogue.title,
        content: content,
        status: '0' // 0表示正常状态
      };
      
      // 如果存在conversationId，则执行更新操作，否则执行添加操作
      let url = '/interview/conversation/add';
      let method = 'POST';
      
      if (this.conversationId) {
        url = `/interview/conversation/edit`;
        method = 'PUT';
        params.conversationId = this.conversationId;
      }
      
      // 发送请求到服务器
      this.$request(url, method, params,{'content-type': 'application/json'})
        .then(res => {
          console.log('对话记录上传成功', res);
        }).catch(err => {
          console.error('对话记录上传失败', err);
        });
    },
    
    // 获取对话详情
    getConversationDetail(conversationId) {
      console.log('开始获取对话详情，ID:', conversationId);
      this.$request(`/interview/conversation/${conversationId}`, 'GET')
        .then(res => {
          console.log('获取对话详情响应:', res);
          if (res.code === 200) {
            const data = res.data;
            // 设置对话标题
            this.dialogue = {
              title: data.title
            };
            
            // 解析对话内容
            try {
              const content = JSON.parse(data.content);
              if (Array.isArray(content)) {
                this.messages = content;
              } else {
                // 如果解析后不是数组，可能是单个对象
                this.messages = [content];
              }
              console.log('解析后的消息:', this.messages);
            } catch (e) {
              console.error('解析对话内容失败:', e);
              // 如果解析失败，将原始内容作为单条消息处理
              this.messages = [{
                role: 'assistant',
                content: data.content,
                time: this.formatTime(new Date())
              }];
            }
            
            // 滚动到底部
            this.$nextTick(() => {
              this.scrollToBottom();
            });
          } else {
            console.error('获取对话详情失败:', res.msg);
            uni.showToast({
              title: '获取对话详情失败',
              icon: 'none'
            });
          }
        })
        .catch(err => {
          console.error('获取对话详情失败:', err);
          uni.showToast({
            title: '网络错误',
            icon: 'none'
          });
        });
    },

  }
};
</script>

<style>
/* 添加连接状态样式 */
.connection-status {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.status-text {
  margin-left: 10px;
  color: #666;
  font-size: 14px;
}

.container {
  padding: 20px;
  padding-bottom: env(safe-area-inset-bottom);
  display: flex;
  flex-direction: column;
  background-color: var(--bg-secondary);
  overflow: hidden;
}

.content {
  flex: 1;
  overflow-y: auto;
  height: calc(100vh - 80px);
}

.message-list {
  padding: 10px 0;
}

.message {
  display: flex;
  flex-direction: column;
  margin-bottom: 20px;
}

.message.user {
  align-items: flex-end;
}

.message.assistant {
  align-items: flex-start;
}

.message-content {
  max-width: 90%;
  padding: 2px 16px;
  border-radius: 18px;
  margin-bottom: 4px;
}

.message.user .message-content {
  background-color: var(--primary-color);
  color: var(--white-color);
  border-bottom-right-radius: 4px;
}

.message.assistant .message-content {
  background-color: var(--bg-primary);
  color: var(--text-primary);
  border-bottom-left-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.message-time {
  font-size: 12px;
  color: var(--text-placeholder);
  margin: 0 10px;
}

.input-container {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 20px;
  display: flex;
  padding: 5px 10px;
  margin:0 3%;
  background-color: var(--bg-primary);
  border-top: 1px solid var(--border-color);
  align-items: center;
  transition: bottom 0.3s ease; /* 添加过渡动画 */
  border-radius: 10px;;
  box-shadow: 1px 1px 20px 0px #aeaeae45;
}

.message-input {
  flex: 1;
  padding: 10px 15px;
  border-radius: 20px;
  font-size: 16px;
  margin-right: 10px;
}

.flooer_rpic {
  width: 48rpx;
  height: 48rpx;
  margin: 0 8px;
}

.typing-indicator {
  display: flex;
  padding: 5px 0;
}

.dot {
  width: 8px;
  height: 8px;
  background-color: #999999;
  border-radius: 50%;
  margin: 0 2px;
  animation: typing 1.4s infinite ease-in-out;
}

.dot:nth-child(1) {
  animation-delay: 0s;
}

.dot:nth-child(2) {
  animation-delay: 0.2s;
}

.dot:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes typing {
  0%, 60%, 100% {
    transform: translateY(0);
  }
  30% {
    transform: translateY(-5px);
  }
}
</style>